﻿using NetSync.Core;
using NetSync.Rabbitmq;

namespace NetSync.Test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var config = new RabbitMQConfig
            {
                Address = "localhost:5672",
                User = "guest",
                Password = "guest",
                ConsumerCountPerGroup = 1,
                NewConnectionPerSend = true
            };
            var serialize = new NewtonsoftJsonNetSerialize();
            INetConnection connection = new NetRabbitMQConnection(serialize);
            connection.ConnectionEvent += Connection_ConnectionEvent;
            connection.DispatchMessageEvent += Connection_DispatchMessageEvent;
            var waitSync = new MemoryWaitSync();
            INetSync<MessageBase, MessageBase> netSync = new TestNetSync(connection, waitSync);
            connection.InitAsync(config).ConfigureAwait(false).GetAwaiter().GetResult();
            var subscribeInfos = new List<SubscribeInfo>()
            {
                new SubscribeInfo()
                {
                    Topic = "RMS_eqp01",
                    Group = "RMS_eqp01"
                },
                 new SubscribeInfo()
                {
                    Topic = "test2",
                    Group = "test2"
                }
            };
            var request = new MessageInfo<string>
            {
                Header = new MessageHeader
                {
                    EqpCode = "eqp01",
                    TransactionId = Guid.NewGuid().ToString(),
                    Direction = DirectionTypeEnum.Request,
                },
                Body = "测试消息"
            };
            connection.SubscribeAsync(subscribeInfos).GetAwaiter().GetResult();
            var result = netSync.SendReplyAsync<MessageBase>("RMS_QUEUE", request, 1200).GetAwaiter().GetResult();
            Console.ReadKey();
            Console.WriteLine("Hello, World!");
        }

        private static void Connection_DispatchMessageEvent(object? sender, DispatchEventArgs e)
        {
            Console.WriteLine($"数据是否已处理：{e.IsHandled}");
        }

        private static void Connection_ConnectionEvent(object? sender, ConnectionEventArgs e)
        {
            Console.WriteLine($"{e.ConncetionType.ToString()}:{e.Message}");
        }
    }

    public class TestNetSync : NetSyncAbstract<MessageBase, MessageBase>
    {
        public TestNetSync(INetConnection connection, IWaitSync waitSync) : base(connection, waitSync)
        {
        }

        public override Func<MessageBase, MessageBase, string> MsgIdFunc => (req, rep) =>
        {
            return req == null ? rep.Header.TransactionId : req.Header.TransactionId;
        };

    }
}